import { useRef, useState } from "react";
import "./index.less";
import * as THREE from "three";
import { reducer } from "../../utils/dva17";
import { NMold, RSetState } from "../../config/constants";
import { isMobile } from "../../utils";

const radius = 100; // 摇杆半径

export default () => {
  if (!isMobile) return null; // 非手机端不显示摇杆

  const [stick, setStick] = useState(false); // 摇杆是否按下
  const [joyPos, setJoyPos] = useState({ x: 0, y: 0 }); // 摇杆出现位置
  const [stickPos, setStickPos] = useState({ x: 0, y: 0 }); // 摇杆相对移动位置
  const [click, setClick] = useState(false); // 按钮是否按下

  const joyStick: any = useRef();
  const stickBox: any = useRef();

  // 摇杆按下
  function keyDown(e: any) {
    setJoyPos({
      x: e.touches[0].clientX - radius,
      y: e.touches[0].clientY - radius,
    });
    setStick(true);
  }
  // 摇杆松开
  function keyUp() {
    joyStick.current?.classList.remove("appear");
    joyStick.current?.classList.add("disappear");
    const stickPos = new THREE.Vector3(0, 0);
    reducer(NMold, RSetState, { direction: stickPos });
    setStickPos(stickPos);
    setTimeout(() => {
      setStick(false);
    }, 200);
  }
  // 摇杆移动
  function keyMove(e: any) {
    if (stick) {
      let stickPosX = e.touches[0].clientX - joyPos.x - radius;
      let stickPosY = e.touches[0].clientY - joyPos.y - radius;

      const stickPos = new THREE.Vector3(stickPosX, stickPosY); // 左右移动
      if (stickPos.length() > radius) {
        stickPos.multiplyScalar(radius / stickPos.length());
      }
      setStickPos(stickPos);
      let direction = new THREE.Vector3(stickPos.x, 0, stickPos.y);
      reducer(NMold, RSetState, { direction });
    }
  }
  // 按下按钮
  function clickStart(e) {
    e.stopPropagation();
    setClick(true);
    reducer(NMold, RSetState, { action: true });
  }
  // 松开按钮
  function clickEnd(e) {
    e.stopPropagation();
    setClick(false);
    reducer(NMold, RSetState, { action: false });
  }
  return (
    <div
      className="rocker"
      onTouchStart={keyDown}
      onTouchEnd={keyUp}
      onTouchMove={keyMove}
    >
      {stick && (
        <div
          ref={joyStick}
          className="joystick appear"
          style={{ left: joyPos.x, top: joyPos.y }}
        >
          <div className="stickBox">
            <div
              ref={stickBox}
              className="stick"
              style={{ left: stickPos.x, top: stickPos.y }}
            />
          </div>
        </div>
      )}

      <div
        className={click ? "button click" : "button"}
        onTouchStart={clickStart}
        onTouchEnd={clickEnd}
      ></div>
    </div>
  );
};
